from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.models import db
from app.models.user import User
from app.utils.auth import require_permission, get_current_user

users_bp = Blueprint('users', __name__)

@users_bp.route('', methods=['GET'])
@require_permission('user.view')
def get_users():
    """获取用户列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '')
        
        query = User.query
        
        if search:
            query = query.filter(
                db.or_(
                    User.username.contains(search),
                    User.email.contains(search)
                )
            )
        
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        return jsonify({
            'users': [user.to_dict() for user in pagination.items],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@users_bp.route('', methods=['POST'])
@require_permission('user.create')
def create_user():
    """创建用户"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = [
            'username', 'email', 'password', 'name', 'employee_id', 'phone', 
            'position', 'department', 'role', 'id_card', 'ethnicity', 
            'gender', 'hire_date', 'is_driver'
        ]
        for field in required_fields:
            if field == 'is_driver':
                # 布尔字段特殊处理
                if field not in data:
                    return jsonify({'error': f'{field} 不能为空'}), 400
            else:
                if not data.get(field):
                    return jsonify({'error': f'{field} 不能为空'}), 400
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=data['username']).first():
            return jsonify({'error': '用户名已存在'}), 400
        
        # 检查邮箱是否已存在
        if User.query.filter_by(email=data['email']).first():
            return jsonify({'error': '邮箱已存在'}), 400
        
        # 检查工号是否已存在
        if data.get('employee_id'):
            if User.query.filter_by(employee_id=data['employee_id']).first():
                return jsonify({'error': '工号已存在'}), 400
        
        # 检查身份证号是否已存在
        if data.get('id_card'):
            if User.query.filter_by(id_card=data['id_card']).first():
                return jsonify({'error': '身份证号已存在'}), 400
        
        # 验证身份证号与性别对应关系
        if data.get('id_card') and data.get('gender'):
            id_card = data['id_card']
            gender = data['gender']
            if len(id_card) == 18:
                # 身份证号第17位数字，奇数为男性，偶数为女性
                gender_digit = int(id_card[16])
                is_id_card_male = gender_digit % 2 == 1
                is_form_male = gender == 'male'
                
                if is_id_card_male != is_form_male:
                    expected_gender = '男' if is_id_card_male else '女'
                    return jsonify({'error': f'根据身份证号，性别应为{expected_gender}'}), 400
        
        from datetime import datetime
        
        # 处理日期字段
        hire_date = None
        if data.get('hire_date'):
            try:
                hire_date = datetime.strptime(data['hire_date'], '%Y-%m-%d').date()
            except ValueError:
                return jsonify({'error': '入职时间格式错误，应为YYYY-MM-DD'}), 400
        
        resignation_date = None
        if data.get('resignation_date'):
            try:
                resignation_date = datetime.strptime(data['resignation_date'], '%Y-%m-%d').date()
            except ValueError:
                return jsonify({'error': '离职时间格式错误，应为YYYY-MM-DD'}), 400
        
        electrician_cert_expiry = None
        if data.get('electrician_cert_expiry'):
            try:
                electrician_cert_expiry = datetime.strptime(data['electrician_cert_expiry'], '%Y-%m-%d').date()
            except ValueError:
                return jsonify({'error': '电工证有效时间格式错误，应为YYYY-MM-DD'}), 400
        
        height_cert_expiry = None
        if data.get('height_cert_expiry'):
            try:
                height_cert_expiry = datetime.strptime(data['height_cert_expiry'], '%Y-%m-%d').date()
            except ValueError:
                return jsonify({'error': '登高证有效时间格式错误，应为YYYY-MM-DD'}), 400
        
        user = User(
            username=data['username'],
            email=data['email'],
            name=data['name'],
            employee_id=data['employee_id'],
            phone=data['phone'],
            position=data['position'],
            department=data['department'],
            role=data.get('role', 'user'),
            group_id=data.get('group_id'),
            # 新增必填字段

            id_card=data['id_card'],
            ethnicity=data['ethnicity'],
            gender=data['gender'],
            hire_date=hire_date,
            is_driver=data['is_driver'],
            # 新增可选字段
            password_field=data.get('password_field'),
            status=data.get('status', 'active'),
            resignation_date=resignation_date,
            electrician_cert_expiry=electrician_cert_expiry,
            height_cert_expiry=height_cert_expiry,
            batch_number=data.get('batch_number'),
            remarks=data.get('remarks')
        )
        user.set_password(data['password'])
        
        # 处理技能列表
        if data.get('skills'):
            user.set_skills_list(data['skills'])
        
        # 处理区域
        if data.get('area_id'):
            user.area_id = data['area_id']
        
        db.session.add(user)
        db.session.commit()
        
        return jsonify({'user': user.to_dict()}), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@users_bp.route('/<int:user_id>', methods=['PUT'])
@require_permission('user.edit')
def update_user(user_id):
    """更新用户"""
    try:
        user = User.query.get_or_404(user_id)
        data = request.get_json()
        
        # 检查用户名是否已被其他用户使用
        if 'username' in data and data['username'] != user.username:
            if User.query.filter_by(username=data['username']).first():
                return jsonify({'error': '用户名已存在'}), 400
            user.username = data['username']
        
        # 检查邮箱是否已被其他用户使用
        if 'email' in data and data['email'] != user.email:
            if User.query.filter_by(email=data['email']).first():
                return jsonify({'error': '邮箱已存在'}), 400
            user.email = data['email']
        
        # 检查工号是否已被其他用户使用
        if 'employee_id' in data and data['employee_id'] != user.employee_id:
            if data['employee_id'] and User.query.filter_by(employee_id=data['employee_id']).first():
                return jsonify({'error': '工号已存在'}), 400
            user.employee_id = data['employee_id']
        
        # 检查身份证号是否已被其他用户使用
        if 'id_card' in data and data['id_card'] != user.id_card:
            if data['id_card'] and User.query.filter_by(id_card=data['id_card']).first():
                return jsonify({'error': '身份证号已存在'}), 400
        
        # 验证身份证号与性别对应关系
        id_card_to_check = data.get('id_card', user.id_card)
        gender_to_check = data.get('gender', user.gender)
        if id_card_to_check and gender_to_check and len(id_card_to_check) == 18:
            # 身份证号第17位数字，奇数为男性，偶数为女性
            gender_digit = int(id_card_to_check[16])
            is_id_card_male = gender_digit % 2 == 1
            is_form_male = gender_to_check == 'male'
            
            if is_id_card_male != is_form_male:
                expected_gender = '男' if is_id_card_male else '女'
                return jsonify({'error': f'根据身份证号，性别应为{expected_gender}'}), 400
        
        # 更新用户认证字段
        if 'role' in data:
            user.role = data['role']
        if 'group_id' in data:
            user.group_id = data['group_id']
        if 'is_active' in data:
            user.is_active = data['is_active']
        if 'password' in data and data['password']:
            user.set_password(data['password'])
        
        # 更新人员信息字段
        personnel_fields = [
            'name', 'phone', 'position', 'department', 'id_card', 
            'ethnicity', 'gender', 'is_driver', 'password_field', 'status', 
            'batch_number', 'remarks'
        ]
        for field in personnel_fields:
            if field in data:
                setattr(user, field, data[field])
        
        # 处理区域（支持多区域）
        if 'area' in data:
            from app.models.area import Area
            from app.models.user_area import UserArea
            
            # 清除现有的多区域关联
            UserArea.query.filter_by(user_id=user.id).delete()
            
            if data['area'] and len(data['area']) > 0:
                area_names = data['area'] if isinstance(data['area'], list) else [data['area']]
                
                # 验证所有区域是否存在
                areas = []
                for area_name in area_names:
                    area = Area.query.filter_by(name=area_name, is_active=True).first()
                    if area:
                        areas.append(area)
                    else:
                        return jsonify({'error': f'区域 "{area_name}" 不存在'}), 400
                
                # 创建新的多区域关联
                for area in areas:
                    user_area = UserArea(user_id=user.id, area_id=area.id)
                    db.session.add(user_area)
                
                # 为了向后兼容，设置第一个区域为主区域
                if areas:
                    user.area_id = areas[0].id
                else:
                    user.area_id = None
            else:
                user.area_id = None
        elif 'area_id' in data:
            user.area_id = data['area_id']
        
        # 处理日期字段
        date_fields = ['hire_date', 'resignation_date', 'electrician_cert_expiry', 'height_cert_expiry']
        for field in date_fields:
            if field in data:
                if data[field]:
                    try:
                        from datetime import datetime
                        date_value = datetime.strptime(data[field], '%Y-%m-%d').date()
                        setattr(user, field, date_value)
                    except ValueError:
                        return jsonify({'error': f'{field}格式错误，应为YYYY-MM-DD'}), 400
                else:
                    setattr(user, field, None)
        
        # 处理技能列表
        if 'skills' in data:
            user.set_skills_list(data['skills'])
        
        db.session.commit()
        
        return jsonify({'user': user.to_dict()}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@users_bp.route('/<int:user_id>', methods=['DELETE'])
@require_permission('user.delete')
def delete_user(user_id):
    """删除用户"""
    try:
        user = User.query.get_or_404(user_id)
        
        # 不能删除自己
        current_user = get_current_user()
        if user.id == current_user.id:
            return jsonify({'error': '不能删除自己'}), 400
        
        db.session.delete(user)
        db.session.commit()
        
        return jsonify({'message': '用户删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500
